<template>
    <div class="container">
        <div class="header">
            <el-input
                class="header-input"
                placeholder="输入店铺名称"
                v-model="findCondition.keywords"
                @keyup.enter="init"
            />
            <el-button type="primary" @click="addService"> + 新增服务</el-button>
        </div>
        <div class="content">
            <el-table :data="serviceList" border style="width: 100%">
                <el-table-column label="店铺名称">
                    <template #default="scope">
                        <el-tooltip
                            class="box-item"
                            effect="dark"
                            :content="scope.row.shopName"
                            placement="top-start"
                        >
                            <p style="overflow: hidden; text-overflow: ellipsis; text-wrap: nowrap">
                                {{ scope.row.shopName }}
                            </p>
                        </el-tooltip>
                    </template>
                </el-table-column>

                <el-table-column prop="category" label="类型" width="70" />
                <el-table-column label="服务点" width="120">
                    <template #default="scope">
                        <el-tooltip
                            class="box-item"
                            effect="dark"
                            :content="scope.row.service_point"
                            placement="top-start"
                        >
                            <p style="overflow: hidden; text-overflow: ellipsis; text-wrap: nowrap">
                                {{ scope.row.service_point }}
                            </p>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column prop="money" label="价格" width="70" />
                <el-table-column label="描述" width="300">
                    <template #default="scope">
                        <el-tooltip
                            class="box-item"
                            effect="dark"
                            :content="scope.row.description"
                            placement="top-start"
                        >
                            <p style="overflow: hidden; text-overflow: ellipsis; text-wrap: nowrap">
                                {{ scope.row.description }}
                            </p>
                        </el-tooltip>
                    </template>
                </el-table-column>

                <el-table-column label="操作" width="100">
                    <template #default="scope">
                        <el-button type="text" @click="handleEdit(scope.$index, scope.row)"
                            >详情</el-button
                        >
                        <el-button
                            type="text"
                            style="color: red"
                            @click="handleDelete(scope.$index, scope.row)"
                            >删除</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>

            <el-drawer
                size="40%"
                v-model="addIsDialog"
                :title="type === 'create' ? '新增' : '编辑'"
            >
                <div>
                    <el-form
                        ref="ruleFormRef"
                        style="max-width: 600px"
                        :model="dataForm"
                        :rules="rules"
                        label-width="auto"
                        class="demo-ruleForm"
                        status-icon
                    >
                        <el-form-item label="类型" prop="category">
                            <el-select v-model="dataForm.category" placeholder="请选择类型">
                                <el-option
                                    v-for="item in typeOpt"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                            /></el-select>
                        </el-form-item>
                        <el-form-item label="省/市">
                            <el-cascader
                                :options="mapList"
                                @change="handleChangeCity"
                                placeholder="请选择地区"
                            />
                        </el-form-item>
                        <el-form-item label="店铺名称" prop="shopNameId">
                            <el-select v-model="dataForm.shopNameId" placeholder="请选择店铺">
                                <el-option
                                    v-for="item in shopList"
                                    :key="item.shopId"
                                    :label="item.shopName"
                                    :value="item.shopId"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="服务点" prop="service_point">
                            <el-select v-model="dataForm.service_point" placeholder="请选择服务点">
                                <el-option
                                    v-for="item in servicePointOpt"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="服务金额" prop="money">
                            <el-input
                                v-model="dataForm.money"
                                type="number"
                                placeholder="请输入数字金额"
                            />
                        </el-form-item>
                        <el-form-item label="服务图片">
                            <el-upload
                                multiple
                                name="files"
                                class="avatar-uploader"
                                :action="servicePort + '/api/upload/doAdds_service'"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload"
                                :headers="authorization"
                            >
                                <img
                                    v-for="item in serviceImgs"
                                    :src="servicePort + item?.url"
                                    class="avatar"
                                />
                                <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
                            </el-upload>
                        </el-form-item>
                        <el-form-item label="服务描述" prop="description">
                            <el-input
                                v-model="dataForm.description"
                                :rows="3"
                                type="textarea"
                                placeholder="请输入服务描述"
                            />
                        </el-form-item>
                    </el-form>
                    <div class="dialog-footer">
                        <el-button @click="addIsDialog = false">取消</el-button>
                        <el-button type="primary" @click="onFinish"> 确定 </el-button>
                    </div>
                </div>
            </el-drawer>
        </div>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { getShopService, getShopList, addService as publishService } from '../../../api/service'
import { getMapList } from '../../../api'
import { useUserInfo } from '../../../store'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import type { UploadProps } from 'element-plus'
import { servicePort } from '../../../request'
const { userInfo } = useUserInfo()
let serviceList = ref<Record<string, any>[]>([])
const addIsDialog = ref(false)
const findCondition = reactive({
    keywords: ''
})

let serviceImgs = ref<string[]>([])

const authorization = {
    authorization: 'Bearer ' + localStorage.getItem('vehicle_web_token') || ''
}

// 该用户拥有的店铺列表
let shopList = ref([])
const type = ref('create')
let mapList = ref([])

const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
    serviceImgs.value = [...serviceImgs.value, ...response.data.list]
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (serviceImgs.value.length > 4) {
        ElMessage({
            message: '最多只能上传五张图片',
            type: 'error'
        })
        return false
    }
    if (!['image/jpeg', 'image/jpg', 'image/png'].includes(rawFile.type)) {
        ElMessage.error(`图片格式错误 ${rawFile.type}`)
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
}

// 新增表单
const dataForm = reactive({
    category: '',
    province: '',
    city: '',
    shopNameId: '',
    service_point: '',
    money: '',
    description: ''
})
const rules = reactive({
    name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
    region: [{ required: true, message: '请选择活动区域', trigger: 'change' }]
})

const init = async () => {
    const { data: data } = await getShopService(findCondition)
    serviceList.value = [...data.data]
}
init()

// 省市发生改变
const handleChangeCity = (value: Array<string>) => {
    dataForm.province = value[0]
    dataForm.city = value[1]
}

// 类型选项
const typeOpt = [
    {
        value: '保养',
        label: '保养'
    },
    {
        value: '维修',
        label: '维修'
    }
]

// 服务点选项
const servicePointOpt = [
    {
        value: '机械维修',
        label: '机械维修'
    },
    {
        value: '车身修复/喷漆',
        label: '车身修复/喷漆'
    },
    {
        value: '油漆保护/车身包装',
        label: '油漆保护/车身包装'
    },
    {
        value: '轮胎/轮毂',
        label: '轮胎/轮毂'
    },
    {
        value: '空调/加热',
        label: '空调/加热'
    },
    {
        value: '保养',
        label: '保养'
    },
    {
        value: '清洁/维护',
        label: '清洁/维护'
    },
    {
        value: '电气系统',
        label: '电气系统'
    },
    {
        value: '电子设备/系统维修',
        label: '电子设备/系统维修'
    },
    {
        value: '电池更换',
        label: '电池更换'
    }
]

// 新增服务
const addService = async () => {
    type.value = 'create'
    addIsDialog.value = true
    const res = await getMapList({ province: userInfo?.province })
    mapList.value = res.data.result || []
    const { data } = await getShopList()
    shopList.value = data.data
}

//确定新增
const onFinish = async () => {
    const params = {
        ...dataForm,
        serviceImgs: serviceImgs.value
    }
    const res = await publishService(params)
    if (res.data.code !== 900) return ElMessage.error(res.data.msg)
    ElMessage.success(res.data.msg)
    addIsDialog.value = false
    init()
    serviceImgs.value = []
    dataForm.category = ''
    dataForm.province = ''
    dataForm.city = ''
    dataForm.shopNameId = ''
    dataForm.service_point = ''
    dataForm.money = ''
    dataForm.description = ''
}

const handleEdit = (index: number, row: any) => {
    console.log(index, row)
}

const handleDelete = (index: number, row: any) => {
    console.log(index, row)
}
</script>

<style scoped>
.container {
    .header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 30px;
        .header-input {
            width: 200px;
        }
    }
    .content {
        margin-bottom: 20px;
    }
    .avatar-uploader .avatar {
        width: 80px;
        height: 80px;
        display: block;
    }
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    text-align: center;
}
</style>
